package com.amar.dtadmin.apidoc.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.amar.dtadmin.apidoc.action.DtAdminApiDocActionGroup;
import com.amar.dtadmin.apidoc.constant.TypeEnum;
import com.amar.dtadmin.apidoc.model.ApiDocCreateReq;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author xiaoshiqiang
 * @since 2025/2/12
 */
public class CurlUtil {
    public static String generateCurl(DtAdminApiDocActionGroup.ApiInfo apiInfo) {
        List<ApiDocCreateReq.ParamItem> paramItems = ParamItemConvertUtil.convert(apiInfo.getInputClass(), "REQUEST");
        LinkedHashMap<String, Object> publicParam = new LinkedHashMap<>() {{
            put("traceid", apiInfo.getApi());
            put("transcode", apiInfo.getApi());
            put("params", "");
            put("source", "app-数据接口服务");
            put("userid", "EDS");
            put("orgid", "EDS");
            put("account", "EDS");
        }};
        LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>();
        paramItems.forEach(param -> paramMap.put(param.getName(), getDefaultValue(param)));
        paramMap.computeIfPresent("pageIndex", (k, v) -> 1);
        paramMap.computeIfPresent("pageSize", (k, v) -> 10);
        publicParam.put("params", paramMap);
        return """
                 curl --request POST \\
                   --url /api/gateway \\
                   --header 'Content-Type: application/json;charset=utf-8' \\
                   --data '%s'
                """.formatted(JSONUtil.toJsonPrettyStr(publicParam));
    }

    private static Object getDefaultValue(ApiDocCreateReq.ParamItem paramItem) {
        return switch (TypeEnum.getEnumByType(paramItem.getDatatype())) {
            case VARCHAR, TEXT, MEDIUMTEXT, LONGTEXT -> "";
            case NUMBER -> 0;
            case DECIMAL -> 0.0;
            case BOOLEAN -> false;
            case ARRAY, JSONARRAY -> new Object[]{};
            case JSONOBJECT -> {
                if (CollUtil.isNotEmpty(paramItem.getNextnode())) {
                    LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>();
                    paramItem.getNextnode().forEach(param -> paramMap.put(param.getName(), getDefaultValue(param)));
                    yield paramMap;
                } else {
                    yield new Object();
                }
            }
            default -> new Object();
        };
    }
}
